package com.fg.ihr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fg.ihr.common.AgeUtil;
import com.fg.ihr.common.MyException;
import com.fg.ihr.common.StringtoInteger;
import com.fg.ihr.domain.*;
import com.fg.ihr.repository.*;
import com.fg.ihr.service.UserService;
import com.fg.ihr.service.serviceImpl.UserVo.UserListVo;
import com.fg.ihr.service.serviceImpl.UserVo.UserUpdateVo;
import groovyjarjarpicocli.CommandLine;
import org.apache.maven.shared.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${file.downLoadFolder}")
    private String downloadFolder;
    @Autowired
    UserRepository userRepository;

    @Autowired
    UserService userService;

    @Autowired
    LocationRepository locationRepository;
    @Autowired
    DepartmentRepository departmentRepository;
    @Autowired
    WardRepository wardRepository;
    @Autowired
    EducationRepository educationRepository;
    @Autowired
    TitleRepository titleRepository;
    @Autowired
    PositionRepository positionRepository;
    @Autowired
    LevelRepository levelRepository;
    @Autowired
    StatusRepository statusRepository;

    @GetMapping("/")
    public String getMain() {
        return "user_list";
    }

    @GetMapping("/add")
    public String addUser(Model model) {
        List<Ward> wards = wardRepository.findAll();
        List<Education> educations = educationRepository.findAll();
        List<Title> titles = titleRepository.findAll();
        List<Position> pos = positionRepository.findAll();
        List<Level> levels = levelRepository.findAll();
        List<Status> status = statusRepository.findAll();
        model.addAttribute("wards",wards);
        model.addAttribute("educations",educations);
        model.addAttribute("titles",titles);
        model.addAttribute("pos",pos);
        model.addAttribute("levels",levels);
        model.addAttribute("status",status);
        return "user_add";
    }

    @GetMapping(value="/detail/{id}/")
    public ModelAndView userDetail(@PathVariable("id") Integer id,Model model){
        User user = userRepository.getOne(id);
        List<Location> locations = locationRepository.findAll();
        List<Department> departments = departmentRepository.findAll();
        List<Ward> wards = wardRepository.findAll();
        List<Education> educations = educationRepository.findAll();
        List<Title> titles = titleRepository.findAll();
        List<Position> pos = positionRepository.findAll();
        List<Level> levels = levelRepository.findAll();
        List<Status> status = statusRepository.findAll();
        model.addAttribute("locations",locations);
        model.addAttribute("departments",departments);
        model.addAttribute("wards",wards);
        model.addAttribute("educations",educations);
        model.addAttribute("titles",titles);
        model.addAttribute("pos",pos);
        model.addAttribute("levels",levels);
        model.addAttribute("status",status);
        return new ModelAndView("user_detail","user",user);
    }


    @PostMapping(value="/update")
        public String  updateDetail (Model model, @Valid UserUpdateVo usermodel , BindingResult result){
        if(result.hasErrors()){
            model.addAttribute("MSG", "出错啦！");
        }else{
            model.addAttribute("MSG", "提交成功！");
        }
        User user = userRepository.getOne(usermodel.getId());
        //用户名
        if (usermodel.getName() != null) {
            user.setName(usermodel.getName());
        }
        //登录名*
        if (usermodel.getUsername() != null) {
            user.setUsername(usermodel.getUsername());
        }
        //手机号码*
        if(usermodel.getPhonenumber() != null){
            user.setPhonenumber(usermodel.getPhonenumber());
        }
        //护士注册证号码*
        if(usermodel.getRegnumber() != null){
            user.setRegnumber(usermodel.getRegnumber());
        }
        //工号*
        if(usermodel.getWorknumber() != null){
            user.setWorknumber(usermodel.getWorknumber());
        }
        //性别*
        if (usermodel.getSex() != null) {
            user.setSex(usermodel.getSex());
        }
        //出生年月*
        if (usermodel.getBirthday() != null) {
            user.setBirthday(usermodel.getBirthday());
        }
        //入职日期*
        if (usermodel.getRegdate() != null) {
            user.setRegdate(usermodel.getRegdate());
        }
        //银行卡账号*
        if (usermodel.getBankaccount() != null) {
            user.setBankaccount(usermodel.getBankaccount());
        }
        //身份证号码*
        if (usermodel.getIdnumber() != null){
            user.setIdnumber(usermodel.getIdnumber());
        }
        //病房*
        if (usermodel.getWard() != null) {
            Ward ward = wardRepository.getOne(usermodel.getWard());
            user.setWard(ward);
        }
        //学历*
        if (usermodel.getEducation() != null) {
            Education edu = educationRepository.getOne(usermodel.getEducation());
            user.setEducation(edu);
        }
        //能级*
        if (usermodel.getLevel() != null) {
            Level level = levelRepository.getOne(usermodel.getLevel());
            user.setLevel(level);
        }
        //职称*
        if (usermodel.getTitle() !=null) {
            Title title = titleRepository.getOne(usermodel.getTitle());
            user.setTitle(title);
        }
        //状态*
        if (usermodel.getStatus() !=null) {
            Status status = statusRepository.getOne(usermodel.getStatus());
            user.setStatus(status);
        }
        //职务*
        if (usermodel.getPositions().size() != 0) {
                System.out.print("位置是:" + usermodel.getPositions());
                List<Position> positionList = positionRepository.findAllByIds(usermodel.getPositions());
                user.setPositionList(positionList);
            }else{
            user.setPositionList(null);
        }

        userRepository.saveAndFlush(user);
        model.addAttribute("MSG", "用户更新成功！");
        return "user_list";
        }


    @PostMapping(value="/create")
    public String addUser (Model model, @Valid UserUpdateVo usermodel , BindingResult result){
        if(result.hasErrors()){
            model.addAttribute("MSG", "出错啦！");
        }else{
            model.addAttribute("MSG", "提交成功！");
        }
        int cnt = userRepository.selectByName(usermodel.getName());
        if (cnt == 0) {
            User user = new User();
            //用户名*
            if (usermodel.getName() != null) {
                user.setName(usermodel.getName());
            }
            //登录名*
            if (usermodel.getUsername() != null) {
                user.setUsername(usermodel.getUsername());
            }
            //手机号码*
            if(usermodel.getPhonenumber() != null){
                user.setPhonenumber(usermodel.getPhonenumber());
            }
            //护士注册证号码*
            if(usermodel.getRegnumber() != null){
                user.setRegnumber(usermodel.getRegnumber());
            }
            //工号*
            if(usermodel.getWorknumber() != null){
                user.setWorknumber(usermodel.getWorknumber());
            }
            //性别*
            if (usermodel.getSex() != null) {
                user.setSex(usermodel.getSex());
            }
            //出生年月*
            if (usermodel.getBirthday() != null) {
                user.setBirthday(usermodel.getBirthday());
            }
            //入职日期*
            if (usermodel.getRegdate() != null) {
                user.setRegdate(usermodel.getRegdate());
            }
            //银行卡账号*
            if (usermodel.getBankaccount() != null) {
                user.setBankaccount(usermodel.getBankaccount());
            }
            //身份证号码*
            if (usermodel.getIdnumber() != null){
                user.setIdnumber(usermodel.getIdnumber());
            }
            //病房*
            if (usermodel.getWard() != null) {
                Ward ward = wardRepository.getOne(usermodel.getWard());
                user.setWard(ward);
            }
            //学历*
            if (usermodel.getEducation() != null) {
                Education edu = educationRepository.getOne(usermodel.getEducation());
                user.setEducation(edu);
            }
            //能级*
            if (usermodel.getLevel() != null) {
                Level level = levelRepository.getOne(usermodel.getLevel());
                user.setLevel(level);
            }
            //职称*
            if (usermodel.getTitle() !=null) {
                Title title = titleRepository.getOne(usermodel.getTitle());
                user.setTitle(title);
            }
            //状态*
            if (usermodel.getStatus() !=null) {
                Status status = statusRepository.getOne(usermodel.getStatus());
                user.setStatus(status);
            }
            //职务*
            if (usermodel.getPositions() !=null) {
                System.out.print("位置是:" + usermodel.getPositions());
                List<Position> positionList = positionRepository.findAllByIds(usermodel.getPositions());
                user.setPositionList(positionList);
            }
            userRepository.saveAndFlush(user);
            model.addAttribute("MSG", "用户添加成功！");
        }else{
            model.addAttribute("MSG", "用户已存在！");
        }
        List<Ward> wards = wardRepository.findAll();
        List<Education> educations = educationRepository.findAll();
        List<Title> titles = titleRepository.findAll();
        List<Position> pos = positionRepository.findAll();
        List<Level> levels = levelRepository.findAll();
        List<Status> status = statusRepository.findAll();
        model.addAttribute("wards",wards);
        model.addAttribute("educations",educations);
        model.addAttribute("titles",titles);
        model.addAttribute("pos",pos);
        model.addAttribute("levels",levels);
        model.addAttribute("status",status);
        return "user_list";
    }


    @RequestMapping(value = "/fileDownload")
    @ResponseBody
    public String download(HttpServletResponse response) throws Exception {
        String filePath = downloadFolder;
        String filename = "template" + System.currentTimeMillis() + ".xlsx";
        userService.TempExport(filePath + filename);
        File file = new File(filePath + filename);
        FileInputStream fileInputStream = new FileInputStream(file);
        response.setContentType("application/gorce-download");
        // 设置被第三方工具打开,设置下载的文件名
        response.addHeader("Content-disposition", "attachment;fileName=" + filename);
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            System.out.println("----------file download" + filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @PostMapping(value = "/importexcel")
    public String exImport(Model model,@RequestParam("excel") MultipartFile file, HttpSession session) throws Exception{

        boolean a = false;
        String fileName = file.getOriginalFilename();
        try {
            a = userService.batchImport(fileName, file);
        } catch (MyException e) {
            e.printStackTrace();
            model.addAttribute("MSG", e);
        }
        return "user_list";
    }

    @GetMapping(value = "/list")
    @ResponseBody
    public String Users(
                        @RequestParam Integer page,
                        @RequestParam Integer size,
                        @RequestParam(required=false) String levels,
                        @RequestParam(required=false) String search,
                        @RequestParam(required=false) String lid,
                        @RequestParam(required=false)  String wards,
                        @RequestParam(required=false) String departments,
                        @RequestParam(required=false) String positions,
                        @RequestParam(required=false) String educations,
                        @RequestParam(required=false) String titles,
                        @RequestParam(required=false) String status,
                        @RequestParam(value="orderBy",defaultValue="id") String orderBy,
                        @RequestParam(value="sortOrder",defaultValue="asc") String sortOrder) {

        List<Ward> wardList = new ArrayList();
        List<Integer> positionList = new ArrayList();
        List<Integer> educationList = new ArrayList();
        List<Integer> titleList = new ArrayList();
        List<Integer> levelList = new ArrayList();
        List<Integer> statusList = new ArrayList();

        if (positions != null && !positions.equals("[]")){
            positionList.addAll(StringtoInteger.StoI(positions));
        }

        if (educations != null && !educations .equals("[]")){
            educationList.addAll(StringtoInteger.StoI(educations ));
        }

        if (titles != null && !titles.equals("[]")){
            titleList.addAll(StringtoInteger.StoI(titles));
        }

        if (levels != null && !levels.equals("[]")){
            levelList.addAll(StringtoInteger.StoI(levels));
        }

        if (status != null && !status.equals("[]")){
            statusList.addAll(StringtoInteger.StoI(status));
        }
        //Generate ward list
        if (lid != null && !lid.equals("")) {
            Integer id = Integer.parseInt(lid);
            List<Integer> deptIntList = new ArrayList<>();  //科室列表
            List<Department> depts = departmentRepository.findLocationList(id); //找到所有科室
            for (Department dept : depts) {
                deptIntList.add(dept.getId());   //添加找到的科室再去级联查询病房
            }
            System.out.print(deptIntList);
            List<Ward> TempWardListl = wardRepository.findWardList(deptIntList);
            wardList.addAll(TempWardListl);
            if (departments != null && !departments.equals("[]")) {
                wardList.clear();
                List<Ward> TempWardListd2 = wardRepository.findWardList(StringtoInteger.StoI(departments));
                wardList.addAll(TempWardListd2);
                if (wards != null && !wards.equals("[]")) {
                    wardList.clear();
                    for (Integer w : StringtoInteger.StoI(wards)) {
                        Ward ward = new Ward();
                        ward.setId(w);
                        wardList.add(ward);
                    }
                }
            }
        }
//        List<Position> positionList = new ArrayList<Position> ();
        Page<User> userlist = userService.findByPageAndParams(search,wardList,educationList,titleList,positionList,statusList,levelList,page,size,orderBy,sortOrder);
        List<UserListVo> displaylist = new ArrayList<UserListVo>();
        for (User items: userlist.getContent()) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            UserListVo useritem = new UserListVo();
            if (items.getBirthday() != null){
                String birthday = formatter.format(items.getBirthday());
                useritem.setBirthday(birthday);
                try {
                    int  age = AgeUtil.getAge(items.getBirthday());
                    useritem.setAge(age);
                    System.out.println("age=="+age);
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            if (items.getWard() !=null){
                useritem.setWard(items.getWard().getWardname());
                useritem.setDepartment(items.getWard().getDepartment().getName());
                useritem.setLocation(items.getWard().getDepartment().getLocation().getName());
            }

            if (items.getRegdate() !=null){
                String regdate = formatter.format(items.getRegdate());
                useritem.setRegdate(regdate);
                try {
                    int  reg = AgeUtil.getAge(items.getRegdate());
                    useritem.setGrade(reg);
                    System.out.println("reg=="+reg);
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
           if (items.getPositionList() !=null){
               List<String> list1 = new ArrayList<String>();
                for (Position pos:items.getPositionList() ){
                    list1.add(pos.getName());
                }
               String ss = String.join(",", list1);
               useritem.setPositions(ss);
           }

            if (items.getLevel() !=null){
                useritem.setLevel(items.getLevel().getName());
            }

            if (items.getStatus() !=null){
                useritem.setStatus(items.getStatus().getName());
            }

            if (items.getEducation() !=null){
                useritem.setEducation(items.getEducation().getName());
            }
            if(items.getName() !=null) {
                useritem.setName(items.getName());
            }
            useritem.setId(items.getId());
            if (items.getSex().equals(Boolean.TRUE)) {
                useritem.setSex("男");
            }
            else if (items.getSex().equals(Boolean.FALSE)){
                useritem.setSex("女");
            }
            if (items.getIdnumber() != null) {
                useritem.setIdnumber(items.getIdnumber());
            }
            if (items.getBankaccount() !=null ){
            useritem.setBankaccount(items.getBankaccount());
            }
            if (items.getPhonenumber() !=null) {
                useritem.setPhonenumber(items.getPhonenumber());
            }
            if (items.getRegnumber() !=null ) {
                useritem.setRegnumber(items.getRegnumber());
            }
            if (items.getWorknumber() !=null ) {
                useritem.setWorknumber(items.getWorknumber());
            }
           if (items.getTitle() != null){
            useritem.setTitle(items.getTitle().getName());
           }   //职务选择
            displaylist.add(useritem);
        }

        JSONObject result = new JSONObject();
        result.put("page",userlist.getSize());
        result.put("total",userlist.getTotalElements());
        result.put("rows",displaylist);
        System.out.println(result.toJSONString());
        return result.toJSONString();

    }

}